import store from '@/store'
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
/* 
  封装一个函数，判断是否含有登录中存在的地址
*/
function hasUrl(url, next) {
  let result = store.getters.getUserinfo.menus_url.some((item) => item == url)
  if (result) {
    next()
  } else {
    next('/home')
  }
};
// 抽离 路由路线
export const indexRouters = [{
    path: '/menu',
    component: () => import('../views/menu/menu'),
    name: "菜单管理",
    beforeEnter: (to, from, next) => {
      hasUrl('/menu', next)
    }
  },
  {
    path: '/role',
    component: () => import('../views/role/role'),
    name: "角色管理",
    beforeEnter: (to, from, next) => {
      hasUrl('/role', next)
    }
  },
  {
    path: '/admin',
    component: () => import('../views/admin/admin'),
    name: "管理员管理",
    beforeEnter: (to, from, next) => {
      hasUrl('/admin', next)
    }
  },
  {
    path: '/cate',
    component: () => import('../views/cate/cate'),
    name: "商品分类",
    beforeEnter: (to, from, next) => {
      hasUrl('/cate', next)
    }
  },
  {
    path: '/space',
    component: () => import('../views/specs/specs'),
    name: "商品规格",
    beforeEnter: (to, from, next) => {
      hasUrl('/space', next)
    }
  },
  {
    path: '/goods',
    component: () => import('../views/goods/goods'),
    name: "商品管理",
    beforeEnter: (to, from, next) => {
      hasUrl('/goods', next)
    }
  },
  {
    path: '/banner',
    component: () => import('../views/banner/banner'),
    name: "轮播图管理",
    beforeEnter: (to, from, next) => {
      hasUrl('/banner', next)
    }
  },
  {
    path: '/member',
    component: () => import('../views/member/member'),
    name: "会员管理",
    beforeEnter: (to, from, next) => {
      hasUrl('/member', next)
    }
  },
  {
    path: '/seckill',
    component: () => import('../views/seckill/seckill'),
    name: "秒杀管理",
    beforeEnter: (to, from, next) => {
      hasUrl('/seckill', next)
    }
  },
  {
    path: '/map',
    component: () => import('../views/map/map'),
    name: "定位管理",
    beforeEnter: (to, from, next) => {
      hasUrl('/map', next)
    }
  }
]

const routes = [{
    path: '/index',
    component: () => import('../pages/index'),
    children: [{
        path: '/home',
        component: () => import('../views/home')
      },
      ...indexRouters,
      {
        path: '',
        redirect: '/home'
      }
    ]
  },
  {
    path: '/login',
    component: () => import('../pages/login')
  },
  {
    path: '*',
    redirect: '/index'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局登录拦截
router.beforeEach((to, from, next) => {
  // 如果用户去的就设登陆页面
  if (to.path == '/login') {
    next()
    return
  }
  // 如果有登录的信息
  if (store.getters.getUserinfo) {
    next()
    return
  }
  // 以上都不符合直接去往登录页面
  next('/login')
})


export default router